<?php
declare (strict_types=1);

namespace app\command;

use app\webapi\controller\APiRedisServer;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class shelvesOrderTask extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('shelvesordertask')
            ->setDescription('商城订单自动取消任务 * 10分钟取消订单');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('商城订单自动取消任务 * 10分钟取消订单');
        $cancelOrders = Db::query("SELECT * FROM sy_user_order_shelves WHERE state=1 AND pay_state=0 AND NOW()>(create_time + INTERVAL 10 MINUTE)", []);
        if (count($cancelOrders) > 0) {
            foreach ($cancelOrders as $v) {
                $order = $v;
                $allgoods = json_decode($order['goods_info'], true);
                foreach ($allgoods as $agv) {
                    $buy_count = $agv['count'];
                    $goodsInfo = APiRedisServer::selected(3)->hget("shelves_goods_0", $agv['id']);
                    if($goodsInfo == null){
                        $output->writeln("取消订单没有找到相关订单{$goodsInfo['id']}在RClient中");
                    }else{
                        $goodsInfo = json_decode($goodsInfo,true);
                        $goodsInfo['count'] += $buy_count;
                        APiRedisServer::selected(3)->hset("shelves_goods_0", $goodsInfo['id'],json_encode($goodsInfo,JSON_UNESCAPED_UNICODE));
                        if($goodsInfo['cid'] > 0){
                            APiRedisServer::selected(3)->hset("shelves_goods_".$goodsInfo['cid'], $goodsInfo['id'],json_encode($goodsInfo,JSON_UNESCAPED_UNICODE));
                        }
                        APiRedisServer::selected(3)->hincrby("counter_shelves_goods", $goodsInfo['id'],$buy_count);
                    }
                }
                Db::execute("UPDATE sy_user_order_shelves SET state=-1 WHERE order_id=? ", [$order['order_id']]);
            }
        }
        if (count($cancelOrders) > 0) {
            $output->writeln("自动取消商城单数:".count($cancelOrders).'时间::'.date("Y-m-d H:i:s",time()));
        }

    }
}
